/*
 * ConnectedUser.java
 *
 * Created on 27. august 2008, 17:24
 */

package jturbofile.gui;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.Reader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import jturbofile.net.NetCore;
import jturbofile.net.Packet;
import jturbofile.net.PeerThread;
import jturbofile.net.SendFileThread;

/**
 *
 * @author  Rolf
 */
public class ConnectedUserUI extends javax.swing.JPanel implements DropTargetListener {

    private PeerThread peer;
    private SendFileThread sft;
    
    /** Creates new form ConnectedUser */
    public ConnectedUserUI(PeerThread pt) {
        peer = pt;
        
        pt.setConnectedUserUI(this);
        
        initComponents();
        
        jIdLabel.setText(""+peer);
        
        JIncommingLabel.setText("");
        jCurrentFile.setText("");
        
        try {
            new DropTarget(jDropZone, this);
        }
        catch(Exception e) {
            LogPanel.singleton().logln("Error attaching drop target listener: "+e);
        }
    }

    public void setSendFileThread(SendFileThread sft) {
        this.sft = sft;
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jIdLabel = new javax.swing.JLabel();
        jDropZone = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jFileProgress = new javax.swing.JProgressBar();
        jCurrentFile = new javax.swing.JLabel();
        jDisconnect = new javax.swing.JButton();
        jCancel = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        JIncommingLabel = new javax.swing.JLabel();
        jIncommingProgress = new javax.swing.JProgressBar();

        jIdLabel.setText("jLabel1");

        jDropZone.setBackground(new java.awt.Color(255, 255, 0));

        jLabel1.setText("Drop");

        jLabel2.setText("Zone");

        javax.swing.GroupLayout jDropZoneLayout = new javax.swing.GroupLayout(jDropZone);
        jDropZone.setLayout(jDropZoneLayout);
        jDropZoneLayout.setHorizontalGroup(
            jDropZoneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jDropZoneLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addContainerGap(66, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jDropZoneLayout.createSequentialGroup()
                .addContainerGap(65, Short.MAX_VALUE)
                .addComponent(jLabel2)
                .addContainerGap())
        );
        jDropZoneLayout.setVerticalGroup(
            jDropZoneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jDropZoneLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 50, Short.MAX_VALUE)
                .addComponent(jLabel2)
                .addContainerGap())
        );

        jLabel3.setText("Outgoing:");

        jFileProgress.setStringPainted(true);

        jCurrentFile.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jCurrentFile.setText("t");

        jDisconnect.setText("Disconnect");
        jDisconnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jDisconnectActionPerformed(evt);
            }
        });

        jCancel.setText("Cancel");
        jCancel.setEnabled(false);
        jCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCancelActionPerformed(evt);
            }
        });

        jLabel4.setText("Incomming:");

        JIncommingLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        JIncommingLabel.setText("t");

        jIncommingProgress.setStringPainted(true);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jIdLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 294, Short.MAX_VALUE)
                        .addComponent(jDisconnect))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jDropZone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jCancel)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jCurrentFile, javax.swing.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(JIncommingLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 247, Short.MAX_VALUE))
                            .addComponent(jFileProgress, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)
                            .addComponent(jIncommingProgress, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jIdLabel)
                    .addComponent(jDisconnect))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jCurrentFile))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jFileProgress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jCancel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(JIncommingLabel))
                        .addGap(9, 9, 9)
                        .addComponent(jIncommingProgress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jDropZone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(16, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

private void jDisconnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jDisconnectActionPerformed
    Packet p = new Packet(Packet.PacketType.CLOSE);
    peer.sendPacket(p);
    peer.close();
}//GEN-LAST:event_jDisconnectActionPerformed

private void jCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCancelActionPerformed
    try {
        sft.cancelSend();
    }
    catch(Exception e) {
        
    }
    
    sft = null;
}//GEN-LAST:event_jCancelActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel JIncommingLabel;
    private javax.swing.JButton jCancel;
    private javax.swing.JLabel jCurrentFile;
    private javax.swing.JButton jDisconnect;
    private javax.swing.JPanel jDropZone;
    private javax.swing.JProgressBar jFileProgress;
    private javax.swing.JLabel jIdLabel;
    private javax.swing.JProgressBar jIncommingProgress;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    // End of variables declaration//GEN-END:variables

    public void dragEnter(DropTargetDragEvent dtde) {
    }

    public void dragOver(DropTargetDragEvent dtde) {
    }

    public void dropActionChanged(DropTargetDragEvent dtde) {
    }

    public void dragExit(DropTargetEvent dte) {
    }

    public void drop(DropTargetDropEvent dtde) {
        
        try {
            DataFlavor linuxFlavor = new DataFlavor("text/uri-list;class=java.io.Reader");
            Transferable tr = dtde.getTransferable();

            for(DataFlavor df : tr.getTransferDataFlavors()) {
                if( df.isFlavorJavaFileListType() ) {
                    LogPanel.singleton().logln("\t"+df.toString());
                    
                    dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
                    
                    List<File> files = (List<File>) tr.getTransferData(df);
                    
                    NetCore.singleton().sendFiles(files, peer, this);
                    
                    dtde.dropComplete(true);
                    return;
                }
                else if( df.match(linuxFlavor) ) {
                    //Linux workaround
                    dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
                    BufferedReader in = new BufferedReader((Reader) tr.getTransferData(df));

                    List<File> files = new ArrayList<File>();
                    
                    String line = in.readLine();
                    
                    while(line != null) {
                        line = line.trim();
                        
                        LogPanel.singleton().logln("Line: ["+line+"]");
                        
                        if( !line.equals("") ) {
                            URI uri = new URI(line);

                            if( uri != null ) {
                                files.add(new File(uri));
                            }
                        }
                        
                        line = in.readLine();
                    }
                    
                    in.close();
                    
                    LogPanel.singleton().logln("Sending files now!!");
                    
                    NetCore.singleton().sendFiles(files, peer, this);
                    
                    LogPanel.singleton().logln("Done!!");

                    dtde.dropComplete(true);
                    return;
                }
            }
        }
        catch(Exception e) {
            LogPanel.singleton().logln("Error extracting files from drop: "+e);
            e.printStackTrace();
        }
            

        LogPanel.singleton().logln("Drop not recognized: "+dtde);
        Transferable tr = dtde.getTransferable();

        LogPanel.singleton().logln("Avaliable flavors:");
        for(DataFlavor df : tr.getTransferDataFlavors()) {
            LogPanel.singleton().logln("\t"+df.toString());
        }
        
        dtde.rejectDrop();
    }

    public JProgressBar getFileProgressBar() {
        return jFileProgress;
    }

    public JProgressBar getIncommingProgress() {
        return jIncommingProgress;
    }
    
    public JLabel getFileNameLabel() {
        return jCurrentFile;
    }
    
    public JLabel getIncommingLabel() {
        return JIncommingLabel;
    }

    public void startSend() {
        jDisconnect.setEnabled(false);
        jCancel.setEnabled(true);
    }

    public void endSend() {
        jDisconnect.setEnabled(true);
        jCancel.setEnabled(false);
    }
}
